<?php
/**
 * Name: 客户资源业务实现类.
 * User: 董坤鸿
 * Date: 2016/10/11
 * Time: 15:28
 */

namespace App\Services\Repo;

use App\Models\Customer;
use App\Models\Group;
use App\Models\AcceptRecord;
use App\Models\Project;
use App\Models\User;
use App\Services\HelpService;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;

class CustomerRepo implements RepoServiceInterface
{
    public function create(array $_options = null):Model
    {
        $customer = new Customer();
        $attr = $customer->getAllowFields();
        foreach ($attr as $v){
            if (isset($_options[$v])) {
                $customer->$v = $_options[$v];
            }
        }
        $customer->save();
        return $customer;
    }

    /**
     * 客户资源列表
     * @param int $limit
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function read($limit = 0)
    {
        $user = Auth::User();
        $data = HelpService::get_filter();
        $projects = $this->getProjectIds();
        $users = $projects->pluck('users')->flatten()->all();
        $filter = $data['customer'] ?? [];
        if (!$projects->count()) {
            return [
                'total' => 0,
                'data' => [],
            ];
        }
        if (!empty($data['project']['_id'])
            && in_array($data['project']['_id'], $projects->pluck('_id')->all())) {
            $projects = $projects->filter(function ($project) use ($data){
                if ($project->_id === $data['project']['_id'])
                    return true;
            });
            $users = $projects->pluck('users')->flatten()->all();
            if (!empty($data['user']['_id'])
                && in_array($data['user']['_id'], $users)) {
                $input_user = User::find($data['user']['_id']);
                if (!is_null($input_user)) {
                    if ($input_user->group_id === $user->group_id
                        && !$user->isManager) {
                        //
                    } else {
                        $user = $input_user;
                    }
                }
            }
        }
        $project_ids = $projects->pluck('_id')->all();
        //客户经理需过滤认领客户
        if (in_array($user->_id, $users) && !$user->isManager) {
            $customers = Customer::search($filter)
                ->acceptSearch($projects->values()->get(0)->_id, $user->_id);
        } else {
            $customers = Customer::search(array_merge($filter,
                ['project_id' => $project_ids]));
        }
        $customers = $customers
            ->orderBy('created_at', 'desc');
        //分页处理
        if (request()->input('page') === "0"){
            $customers = $customers->get();
            $total = $customers->count();
        } else {
            $customers = $customers->paginate(20);
            $total = $customers->total();
        }
        //web客户库需增加客户经理
        if (!HelpService::fromApp()) {
            $items = $customers->map(function ($data) use ($project_ids) {
                //客户经理
                $users = AcceptRecord::where([
                    'project_id' => ['$in' => $project_ids],
                    'customers' => $data->id,
                ])->get()->pluck('user_id')->all();
                if ($users) {
                    $data->managers = User::select(['name', 'mobile'])
                        ->whereIn('_id', $users)->get()->all();
                } else {
                    $data->managers = [];
                }
                if (isset($data->baseInfo['birthday']) && is_numeric($data->baseInfo['birthday'])) {
                    $baseInfo = $data->baseInfo;
                    $baseInfo['birthday'] = date('Y-m-d', $baseInfo['birthday']);
                    $data->baseInfo = $baseInfo;
                }
                return $data;
            });
            return new LengthAwarePaginator($items,
                $total, 20, request()->input('page', 1));
        }
        return $customers->map(function($customer) {
            return $customer->merge();
        });
    }


    public function find(array $_filter):Model
    {
        $user = Auth::User();
        $customer = Customer::find($_filter)->first();
        // 时间戳转为时间
        if (!empty($customer['baseInfo']['birthday'])) {
            $cusBaseInfo = $customer->baseInfo;
            $cusBaseInfo['birthday'] = date('Y-m-d', $customer['baseInfo']['birthday']);
            $customer->baseInfo = $cusBaseInfo;
        }
        if (!empty($customer['baseInfo']['driverAt'])) {
            $cusBaseInfo = $customer->baseInfo;
            $cusBaseInfo['driverAt'] = date('Y-m-d', $customer['baseInfo']['driverAt']);
            $customer->baseInfo = $cusBaseInfo;
        }
        if (!empty($customer['socialInfo']['shihui']['regDate'])) {
            $cusSocialInfo = $customer->socialInfo;
            $cusSocialInfo['shihui']['regDate'] = date('Y-m-d', $customer['socialInfo']['shihui']['regDate']);
            $customer->socialInfo = $cusSocialInfo;
        }
        // 把houseInfo的id转为string
        if (!empty($customer['houseInfo'])) {
            $houseInfo = [];
            foreach ($customer['houseInfo'] as $k=>$v) {
                // 粗略的判断houseInfo字段的格式
                if (!is_array($v)) {
                    continue;
                }
                if ($k === 'address') {
                    continue;
                }
                if (!empty($v['最近装修时间'])) {
                    $v['最近装修时间'] = date('Y-m-d', $v['最近装修时间']);
                }
                if (!empty($v['租赁时间'])) {
                    $v['租赁时间'][0] = date('Y-m-d', $v['租赁时间'][0]);
                    $v['租赁时间'][1] = date('Y-m-d', $v['租赁时间'][1]);
                }
                if (array_key_exists('_id', $v)) {
                    $v['_id'] = (string)$v['_id'];
                }
                if (array_key_exists('id', $v)) {
                    $v['id'] = (string)$v['id'];
                }
                array_push($houseInfo, $v);
            }
            $customer->houseInfo = $houseInfo;
        }
        return $customer;
    }

    public function update(array $_filter, array $_update_data):bool
    {
        $customer = Customer::find($_filter)->first();
        if (!is_null($customer)){
            $customer->updated_at = time();
            $attr = $customer->getAllowFields();
            $arr = array_keys($customer->getAttributes());
            foreach ($attr as $v){
                if (isset($_update_data[$v])) {
                    if ($v == 'baseInfo') {
                        $baseInfo = $customer->baseInfo;
                        if (is_null($baseInfo)) {
                            $baseInfo = [];
                        }
                        $_update_data[$v] = array_merge($baseInfo, $_update_data[$v]);
                    }
                    if ($v == 'houseInfo') {
                        $houseInfo = $customer->houseInfo;
                        if (empty($houseInfo)) {
                            $houseInfo = [];
                        }
                        $houseUpdate = [];
                        if (!empty($houseInfo)) {
                            foreach ($houseInfo as $k1=>$one) {
                                foreach ($_update_data[$v] as $k2 => $item) {
                                    if ((String)$one['_id'] === (String)$item['_id']) {
                                        unset($houseInfo[$k1]);
                                        unset($_update_data[$v][$k2]);
                                        array_push($houseUpdate, $item);
                                    }
                                }
                            }
                        }
                        if (empty($houseUpdate)) {
                            $_update_data[$v] = array_merge($_update_data[$v], $houseInfo);
                        } else {
                            $temp = array_merge($houseInfo, $houseUpdate);
                            $_update_data[$v] = array_merge($_update_data[$v], $temp);
                        }

                    }
                    if ($v == 'socialInfo') {
                        if (in_array($v, $arr)) {
                            $socialInfo = $customer->socialInfo;
                            if (!is_null($socialInfo)) {
                                if (!empty($socialInfo['email'])) {
                                    $_update_data[$v]['email'] = $socialInfo['email'];
                                }
                                if (!empty($socialInfo['shihui'])) {
                                    if (isset($_update_data[$v]['shihui'])) {
                                        $_update_data[$v]['shihui'] = array_merge($socialInfo['shihui'], $_update_data[$v]['shihui']);
                                    } else {
                                        $_update_data[$v]['shihui'] = $socialInfo['shihui'];
                                    }
                                }
                                if (!empty($socialInfo['weibo'])) {
                                    if (isset($_update_data[$v]['weibo'])) {
                                        $_update_data[$v]['weibo'] = array_merge($socialInfo['weibo'], $_update_data[$v]['weibo']);
                                    } else {
                                        $_update_data[$v]['weibo'] = $socialInfo['weibo'];
                                    }
                                }
                                if (!empty($socialInfo['wechat'])) {
                                    if (isset($_update_data[$v]['wechat'])) {
                                        $_update_data[$v]['wechat'] = array_merge($socialInfo['wechat'], $_update_data[$v]['wechat']);
                                    } else {
                                        $_update_data[$v]['wechat'] = $socialInfo['wechat'];
                                    }
                                }
                                if (!empty($socialInfo['platform'])) {
                                    $_update_data[$v]['platform'] = $socialInfo['platform'];
                                }
                            }
                        }
                    }
                    $customer->$v = $_update_data[$v];
                }
            }
            return $customer->save();
        }else{
            return false;
        }
    }

    public function delete(array $_filter):bool
    {

    }

    /**
     * 获取用户有权限查看的项目
     * @return Collection
     */
    private function getProjectIds():Collection
    {
        $user = Auth::User();
        $group = Group::find($user->group_id);
        $projects = new Collection();
        if (is_null($group)) {
            return $projects;
        }
        $groups = $group->getLeafBy($group->id);
        if (is_array($groups)) {
            $group_ids = array_column($groups, 'id');
            $projects = Project::whereIn('group_id', $group_ids)
                ->get();
        } else {
            $project = Project::where('users', $user->id)
                ->first();
            if (!is_null($project)) {
                $projects->add($project);
            }
        }
        return $projects;
    }

    /**
     *
     * @FunName: findAcceptRecordsById
     * @Param: * @param $_id
     */
    public function findAcceptRecordsById($_id)
    {
        $user = request()->user();
        // 获取当前登录用户能看到的项目
        $project = Project::where('users', $user->_id)->first();
        $project_ids = [];
        // 为空 说明是上层账号
        if (is_null($project)) {
            $group_id = $user->group_id;
            $group = new Group();
            $groups= $group->getLeafBy($group_id);
            $group_ids = array_column($groups, '_id');
            // 循环组织架构id, 找到对应的项目
            foreach ($group_ids as $g) {
                $pro = Project::where('group_id', $g)->first();
                if (!is_null($pro)) {
                    array_push($project_ids, $pro->_id);
                }
            }
        } else {
            $project_ids = array($project->_id);
        }
        $customer = Customer::find($_id);
        // 当前登录的人 能看到的项目  这个客户必须在这个项目中
        if (!$user->can('show', $customer)) {
            return [];
        }
        $acceptRecord_ids = AcceptRecord::whereIn('customers', [$_id])
            ->get()
            ->pluck('_id')
            ->all();
        if (empty($acceptRecord_ids)) {
            return [];
        }
        // 获取当前用户的认领记录并组织数据
        $data = [];
        foreach ($acceptRecord_ids as $one) {
            $parClass = new \stdClass();
            $chiClass = new \stdClass();
            $acceptRecord = AcceptRecord::find($one);
            $project_id = $acceptRecord->project_id;
            if (!in_array($project_id, $project_ids)) {
                continue;
            }
            $user_id = $acceptRecord->user_id;
            $returnUser = User::find($user_id);
            $name = $returnUser->name;
            $status = $returnUser->status;
            $chiClass->_id = $user_id;
            $chiClass->name = $name;
            $chiClass->status = $status;
            $parClass->project_id = $project_id;
            $parClass->user = $chiClass;
            array_push($data, $parClass);
        }
        return $data;
        
    }
}
